package com.lx.yygh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Ordering;
import com.lx.yygh.common.constant.MqConst;
import com.lx.yygh.common.exception.YyghException;
import com.lx.yygh.common.helper.HttpRequestHelper;
import com.lx.yygh.common.result.ResultCodeEnum;
import com.lx.yygh.common.service.RabbitService;
import com.lx.yygh.enums.OrderStatusEnum;
import com.lx.yygh.hosp.client.HospFeignClient;
import com.lx.yygh.mapper.OrderMapper;
import com.lx.yygh.model.order.OrderInfo;
import com.lx.yygh.model.user.Patient;
import com.lx.yygh.model.user.UserInfo;
import com.lx.yygh.service.OrderService;
import com.lx.yygh.service.WeixinService;
import com.lx.yygh.user.client.PatientFeignClient;
import com.lx.yygh.vo.hosp.ScheduleOrderVo;
import com.lx.yygh.vo.msm.MsmVo;
import com.lx.yygh.vo.order.OrderMqVo;
import com.lx.yygh.vo.order.OrderQueryVo;
import com.lx.yygh.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Consumer;

/**
 * @author c先生
 * @date 2022年10月29日 下午 4:52:03
 * @describe
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Resource
    PatientFeignClient patientFeignClient;
    @Resource
    HospFeignClient hospFeignClient;
    @Resource
    RabbitService rabbitService;
    @Autowired
    WeixinService weixinService;

    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //根据patientId获取就诊人信息
        Patient patient = patientFeignClient.getPatientById(patientId);
        if(null == patient) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //根据scheduleId获取排班信息
        ScheduleOrderVo scheduleOrderVo = hospFeignClient.getScheduleOrderVo(scheduleId);
        if(null == scheduleOrderVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //当前时间不可以预约
        if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }
        // SignInfoVo  医院的api的地址   当前医院的签名
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        if(scheduleOrderVo.getAvailableNumber() <= 0) {
            throw new YyghException(ResultCodeEnum.NUMBER_NO);
        }
        //生成订单信息
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        //订单号采用时间戳加随机数来生成
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
//        this.save(orderInfo);
        this.saveOrUpdate(orderInfo);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        //预约挂号平台的mongodb中获取的排班的id=634bee2cf4d80c0cc6b26943
        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        //调用的医院的接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl()+"/order/submitOrder");
        if(result.getInteger("code") != 200){
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        //如果返回的状态码是200 说明调用成功了
        JSONObject jsonObject = result.getJSONObject("data");
        //预约记录唯一标识（医院预约记录主键）
        String hosRecordId = jsonObject.getString("hosRecordId");
        //预约序号
        Integer number = jsonObject.getInteger("number");
        //取号时间
        String fetchTime = jsonObject.getString("fetchTime");
        //取号地址
        String fetchAddress = jsonObject.getString("fetchAddress");
        //更新订单
        orderInfo.setHosRecordId(hosRecordId);
        orderInfo.setNumber(number);
        orderInfo.setFetchTime(fetchTime);
        orderInfo.setFetchAddress(fetchAddress);
        baseMapper.updateById(orderInfo);
        //排班可预约数
        Integer reservedNumber = jsonObject.getInteger("reservedNumber");
        //排班剩余预约数
        Integer availableNumber = jsonObject.getInteger("availableNumber");
        //发送mq信息更新号源和短信通知
        OrderMqVo orderMqVo = new OrderMqVo();
        //下面的三个参数用于修改mongodb中的数据
        orderMqVo.setScheduleId(scheduleId);
        orderMqVo.setReservedNumber(reservedNumber);
        orderMqVo.setAvailableNumber(availableNumber);
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        /*String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime()==0 ? "上午": "下午");*/
           /* Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);*/
        Map<String,Object> param = new HashMap();
        param.put("code","000000");
        msmVo.setParam(param);
        orderMqVo.setMsmVo(msmVo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
        return orderInfo.getId();
    }

    @Override
    public IPage<OrderInfo> getPageList(Integer page, Integer limit, OrderQueryVo orderQueryVo) {
        if(orderQueryVo==null){
            orderQueryVo = new OrderQueryVo();
        }
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        String outTradeNo = orderQueryVo.getOutTradeNo();
        String keyword = orderQueryVo.getKeyword();
        String patientName = orderQueryVo.getPatientName();
        String reserveDate = orderQueryVo.getReserveDate();
        String orderStatus = orderQueryVo.getOrderStatus();
        Long patientId = orderQueryVo.getPatientId();
        Page<OrderInfo> pageParm = new Page<>(page,limit);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(StringUtils.hasText(outTradeNo)){
            wrapper.eq("out_trade_no",outTradeNo);
        }
        if(StringUtils.hasText(keyword)){
            wrapper.like("hosname",keyword);
        }
        if(StringUtils.hasText(patientName)){
            wrapper.eq("patient_name",patientName);
        }
        if(StringUtils.hasText(reserveDate)){
            wrapper.eq("reserve_date",reserveDate);
        }
        if(StringUtils.hasText(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if(StringUtils.hasText(createTimeEnd)){
            wrapper.le("create_time",createTimeEnd);
        }
        if(StringUtils.hasText(orderStatus)){
            wrapper.eq("order_status",orderStatus);
        }
        if(patientId!=null){
            wrapper.eq("patient_id",patientId);
        }
        IPage<OrderInfo> iPage = orderMapper.selectPage(pageParm, wrapper);
        List<OrderInfo> orderInfoList = iPage.getRecords();
        for (OrderInfo orderInfo : orderInfoList) {
            this.packageOrderInfo(orderInfo);
        }
        return iPage;
    }

    private void packageOrderInfo(OrderInfo orderInfo) {
        HashMap<String, Object> map = new HashMap<>();
        Integer orderStatus = orderInfo.getOrderStatus();
        String status = OrderStatusEnum.getStatusNameByStatus(orderStatus);
        map.put("orderStatusString",status);
        orderInfo.setParam(map);
    }

    @Override
    public List<Map<String, Object>>  getStatusList() {
        List<Map<String, Object>> statusList = OrderStatusEnum.getStatusList();
        return statusList;
    }

    @Override
    public OrderInfo getOrderInfoById(Long id) {
        OrderInfo orderInfo = orderMapper.selectById(id);
        this.packageOrderInfo(orderInfo);
        return orderInfo;
    }

    @Override
    public Boolean cancelOrder(Long orderId) {
        //根据id获取订单信息
        OrderInfo orderInfo = orderMapper.selectById(orderId);
        if(orderInfo==null){
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        //已经过了取消预约时间
        if(quitTime.isBeforeNow()){
            throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
        }

        //调用医院接口实现取消预约
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);

        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updateCancelStatus");

        if(result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }else {
            //是否支付 退款
            if(orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
            //已支付 退款
                boolean isRefund = weixinService.refund(orderId);
                if(!isRefund) {
                    throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
            }
            //更改订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(orderInfo);
            //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            //String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
//                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
//                put("reserveDate", reserveDate);
//                put("name", orderInfo.getPatientName());
                put("code","000001");
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        }

        return true;
    }
}
